package L612;

/**
 * @program: javase
 * @description:
 * @author: luolidong
 * @create: 2021-06-12 10:02
 * @version: 1.0
 */
public class Demo1 {
//    m+n;space: O(1)：指针与变量使用常数大小空间。
    public String addStrings(String num1, String num2) {
        if (num1.length() == 0) return num2;
        if (num2.length() == 0) return num1;
        StringBuilder sb = new StringBuilder();
        int i = num1.length() - 1, j = num2.length() - 1, carry = 0;

        while (i >= 0 || j >= 0) {
//            判断哪个为先遍历完，就为0
            int n1 = i >= 0 ? num1.charAt(i) - '0' : 0;
            int n2 = j >= 0 ? num2.charAt(j) - '0' : 0;
            int temp = n1 + n2 + carry;
            carry = temp / 10;//更新进位值
            sb.append(temp % 10);//只添加小于10的
            i--;
            j--;
        }
//        可能两个数同时遍历完，此时还要+‘1’；
        if (carry == 1) sb.append(carry);
//        反转
        return sb.reverse().toString();
    }

    public static void main(String[] args) {
        String s = new Demo1().addStrings("98765689", "76856493");
        System.out.println(98765689 + 76856493);
        System.out.println("s = " + s);
    }
}
